#!/bin/bash
# FFmpeg Android编译脚本
# 使用方法: ./build_ffmpeg_android.sh

set -e  # 遇到错误立即退出

# 默认参数
if [ -z "$ANDROID_NDK_ROOT" ]; then
    if [ -n "$ANDROID_HOME" ]; then
        ANDROID_NDK_ROOT="$ANDROID_HOME/ndk/29.0.13599879"
    else
        # Windows默认路径
        ANDROID_NDK_ROOT="/c/Users/hfqf1/AppData/Local/Android/Sdk/ndk/29.0.13599879"
    fi
fi
BUILD_DIR="./ffmpeg_build"
OUTPUT_DIR="./android/app/src/main/jniLibs"
FFMPEG_VERSION="6.0"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印函数
print_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

print_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

print_error() {
    echo -e "${RED}❌ $1${NC}"
}

# 检查环境
check_environment() {
    print_info "检查编译环境..."
    
    # 检查NDK
    if [ ! -d "$ANDROID_NDK_ROOT" ]; then
        print_error "Android NDK未找到: $ANDROID_NDK_ROOT"
        print_info "请设置ANDROID_NDK_ROOT环境变量"
        exit 1
    fi
    
    # 检查必需工具
    local tools=("curl" "tar" "make")
    for tool in "${tools[@]}"; do
        if ! command -v "$tool" &> /dev/null; then
            print_error "缺少必需工具: $tool"
            exit 1
        fi
    done
    
    # 检查NDK编译器
    if [ ! -f "$ANDROID_NDK_ROOT/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android21-clang" ]; then
        print_error "NDK编译器未找到"
        exit 1
    fi
    
    print_success "环境检查通过"
}

# 下载FFmpeg源码
download_ffmpeg() {
    local ffmpeg_dir="ffmpeg-$FFMPEG_VERSION"
    local ffmpeg_archive="ffmpeg-$FFMPEG_VERSION.tar.bz2"
    local ffmpeg_url="https://ffmpeg.org/releases/ffmpeg-$FFMPEG_VERSION.tar.bz2"
    
    if [ -d "$ffmpeg_dir" ]; then
        print_info "FFmpeg源码已存在，跳过下载"
        return
    fi
    
    print_info "下载FFmpeg源码..."
    if [ ! -f "$ffmpeg_archive" ]; then
        curl -L "$ffmpeg_url" -o "$ffmpeg_archive"
        print_success "下载完成"
    fi
    
    print_info "解压源码..."
    tar -xjf "$ffmpeg_archive"
    print_success "解压完成"
}

# 编译FFmpeg
build_ffmpeg() {
    local arch="$1"
    local cpu="$2"
    local prefix="$3"
    local cross_prefix="$4"
    
    print_info "编译 $arch 架构..."
    
    # 配置参数
    local configure_args=(
        "--prefix=$prefix"
        "--target-os=android"
        "--arch=$arch"
        "--cpu=$cpu"
        "--enable-cross-compile"
        "--cross-prefix=$cross_prefix"
        "--sysroot=$ANDROID_NDK_ROOT/toolchains/llvm/prebuilt/linux-x86_64/sysroot"
        "--enable-shared"
        "--disable-static"
        "--enable-gpl"
        "--enable-version3"
        "--disable-doc"
        "--disable-programs"
        "--disable-ffmpeg"
        "--disable-ffplay"
        "--disable-ffprobe"
        "--disable-avdevice"
        "--disable-avfilter"
        "--disable-postproc"
        "--disable-encoders"
        "--disable-decoders"
        "--enable-decoder=h264"
        "--enable-decoder=h265"
        "--enable-decoder=vp8"
        "--enable-decoder=vp9"
        "--enable-decoder=aac"
        "--enable-decoder=mp3"
        "--enable-decoder=opus"
        "--enable-decoder=vorbis"
        "--enable-decoder=flac"
        "--enable-decoder=wav"
        "--enable-decoder=pcm"
        "--disable-network"
        "--disable-protocols"
        "--disable-filters"
        "--disable-hwaccels"
        "--disable-parsers"
        "--disable-bsfs"
        "--disable-indevs"
        "--disable-outdevs"
        "--disable-devices"
        "--disable-debug"
    )
    
    # 配置
    ./configure "${configure_args[@]}"
    if [ $? -ne 0 ]; then
        print_error "$arch 架构配置失败"
        exit 1
    fi
    
    # 清理
    make clean
    
    # 编译
    make -j$(nproc)
    if [ $? -ne 0 ]; then
        print_error "$arch 架构编译失败"
        exit 1
    fi
    
    # 安装
    make install
    if [ $? -ne 0 ]; then
        print_error "$arch 架构安装失败"
        exit 1
    fi
    
    print_success "$arch 架构编译完成"
}

# 复制库文件
copy_libraries() {
    print_info "复制库文件到项目目录..."
    
    local output_archs=("arm64-v8a" "armeabi-v7a" "x86_64")
    
    for arch in "${output_archs[@]}"; do
        local source_dir="$BUILD_DIR/android/$arch"
        local target_dir="$OUTPUT_DIR/$arch"
        
        mkdir -p "$target_dir"
        
        if [ -d "$source_dir/lib" ]; then
            cp "$source_dir/lib"/*.so "$target_dir/"
            print_success "复制 $arch 库文件"
        else
            print_warning "$arch 库文件未找到"
        fi
    done
    
    # 复制头文件
    local include_source="$BUILD_DIR/android/arm64-v8a/include"
    local include_target="$OUTPUT_DIR/include"
    
    if [ -d "$include_source" ]; then
        mkdir -p "$include_target"
        cp -r "$include_source"/* "$include_target/"
        print_success "复制头文件"
    fi
}

# 主函数
main() {
    print_info "开始FFmpeg Android编译..."
    print_info "NDK路径: $ANDROID_NDK_ROOT"
    print_info "构建目录: $BUILD_DIR"
    print_info "输出目录: $OUTPUT_DIR"
    
    # 检查环境
    check_environment
    
    # 创建构建目录
    mkdir -p "$BUILD_DIR"
    cd "$BUILD_DIR"
    
    # 下载源码
    download_ffmpeg
    
    # 进入FFmpeg目录
    cd "ffmpeg-$FFMPEG_VERSION"
    
    # 设置环境变量
    export ANDROID_NDK_ROOT
    export PATH="$ANDROID_NDK_ROOT/toolchains/llvm/prebuilt/linux-x86_64/bin:$PATH"
    
    # 编译不同架构
    local architectures=(
        "aarch64:armv8-a:$BUILD_DIR/android/arm64-v8a:$ANDROID_NDK_ROOT/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android21-"
        "arm:armv7-a:$BUILD_DIR/android/armeabi-v7a:$ANDROID_NDK_ROOT/toolchains/llvm/prebuilt/linux-x86_64/bin/armv7a-linux-androideabi21-"
        "x86_64:x86_64:$BUILD_DIR/android/x86_64:$ANDROID_NDK_ROOT/toolchains/llvm/prebuilt/linux-x86_64/bin/x86_64-linux-android21-"
    )
    
    for arch_info in "${architectures[@]}"; do
        IFS=':' read -r arch cpu prefix cross_prefix <<< "$arch_info"
        build_ffmpeg "$arch" "$cpu" "$prefix" "$cross_prefix"
    done
    
    # 复制库文件
    copy_libraries
    
    print_success "FFmpeg Android编译完成！"
    print_info "库文件位置: $OUTPUT_DIR"
    print_info "头文件位置: $OUTPUT_DIR/include"
    print_info ""
    print_info "下一步:"
    print_info "  1. 检查库文件是否正确生成"
    print_info "  2. 运行项目测试编译"
    print_info "  3. 验证FFmpeg功能"
}

# 执行主函数
main "$@"